import { queryOtherArticleListByColumnId } from '@/service/article-column';
import type { ActionType } from '@ant-design/pro-components';
import { ModalForm, ProTable } from '@ant-design/pro-components';
import { useParams } from '@umijs/max';
import { message } from 'antd';
import type { Key } from 'react';
import { useRef, useState } from 'react';

const columns = [
  {
    title: '文章id',
    dataIndex: 'id',
    width: 60,
  },
  {
    title: '文章标题',
    dataIndex: 'title',
    width: 200,
  },
  {
    title: '创建时间',
    dataIndex: 'createdTime',
    width: 100,
  },
]

const AddColumnModal: React.FC = ({open, onOpenChange, onFinish }) => {
  const { id } = useParams();
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);

  // 表格查询
  const tableSearch = async (params) => {
    let values = {
      pageNum: params.current,
      pageSize: params.pageSize,
    };

    const res = await queryOtherArticleListByColumnId(id, values);

    return { success: true, data: res?.list || [], total: res?.total || 0 };
  };

  const prevFinish = () => {
    if (!selectedRowKeys?.length) {
      message.error('请勾选要添加至此专栏的文章');
      return;
    }
    onFinish(selectedRowKeys)
  }

  if (!open) {
    return null;
  }

  return (
    <ModalForm
      layout="horizontal"
      width={720}
      title="将文章添加至此专栏"
      open={open}
      onOpenChange={onOpenChange}
      modalProps={{
        destroyOnClose: true,
        onCancel: () => onOpenChange(false),
      }}
      onFinish={prevFinish}
    >
      <ProTable
        actionRef={actionRef}
        rowKey={(item) => item.id}
        rowSelection={{
          selectedRowKeys,
          onChange: (keys: Key[]) => setSelectedRowKeys(keys),
        }}
        request={tableSearch}
        columns={columns}
        defaultSize="small"
        search={false}
        toolBarRender={false}
        scroll={{ x: 'max-content' }}
      />
    </ModalForm>
  );
};

export default AddColumnModal;
